package com.test.controller;

import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.test.common.util.KeyGenerator;
import com.test.model.Article;
import com.test.model.Reply;
import com.test.model.User;

public class ArticleController extends Controller {

	public void add() {
		render("/article_add.jsp");
	}

	public void list() {
        int pageNumber = 1;
        //int pageNumber = getParaToInt("pageNumber");
		StringBuffer sb = new StringBuffer();
		sb.append(" from article a where a.is_delete='1' order by last_reply_date desc");
		Page<Article> page = null;
		String sql = "select a.id,a.title,a.author,date_format(a.publish_date,'%Y-%m-%d %H:%i:%s') publish_date,a.view,a.reply,a.last_reply,date_format(a.last_reply_date,'%Y-%m-%d %H:%i:%s') last_reply_date";
		page = Article.dao.paginate(pageNumber, 10, sql, sb.toString());
		setAttr("page", page);
		render("/article_list.jsp");
	}

	public void save() {
		String id = KeyGenerator.getUUID();
		String title = getPara("title");
		String content = getPara("content");
		User user = (User) getSessionAttr("user");
		String author = user.get("username");
		Article.dao.set("id", id).set("title", title).set("content", content)
				.set("author", author).set("publish_date", new Date())
				.set("is_delete", "1").set("is_top", "0").set("view", 0).set("reply", 0).save();
		render("/article_common.jsp");
	}
	
	public void detail(){
		String id = getPara(0);
		Article article = Article.dao.findById(id);
		Article.dao.findById(id).set("view", article.getInt("view")+1).update();
		setAttr("article", article);
		Page<Reply> page = Reply.dao.paginate(1, 5, "select date_format(reply_date,'%Y-%m-%d %H:%i:%s') reply_date,author,floor,content ", "from reply where article_id = '"+id+"' order by reply_date asc");
		setAttr("page", page);
		render("/article_detail.jsp");
	}
}